//
//  YWAttendanceViewController.m
//  maintain
//
//  Created by Kyo on 16/2/19.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "MBProgressHUD.h"
#import "NSDate+Additions.h"
#import "UIColor+CustomColors.h"
#import "UIImage+Extension.h"
#import "YWAttendanceManager.h"
#import "YWAttendanceRecord.h"
#import "YWAttendanceRecordViewController.h"
#import "YWAttendanceViewController.h"
#import "YWCommonTool.h"
#import "YWConst.h"
#import "YWLocationManager.h"
#import "YWLoginTool.h"
#import "YWMacro.h"
#import "UIView+Extension.h"
#import "YWQrcodeManager.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import "YWPhotoView.h"
#import "YWMeterReadingManager.h"
#import "YWResourceManager.h"
#import "YWEquipmentManager.h"
#import "YWBuildingManager.h"
#import "YWMyAttendanceViewController.h"

#define labelWidth (SCREEN_WIDTH - kMarginW * 2)
#define imageSize (50)
#define gap (10)

#define KDescriptionTextMax 100

@interface YWAttendanceViewController () <UITextViewDelegate,YWPhotoViewDelegate>{
    NSString *locationText;
}
@property (nonatomic, weak) UIScrollView *myScrollView;
@property (nonatomic, weak) UIView* bgView;
@property (nonatomic, weak) UIImageView* locationIV;
@property (nonatomic, weak) UILabel* locationLabel;

@property (nonatomic, weak) UIImageView* attendanceIV;
@property (nonatomic, weak) UILabel* attendanceMan;
@property (nonatomic, weak) UILabel* attendanceTime;
//@property (nonatomic, weak) UILabel *latestAttendanceTimeLabel;

@property (nonatomic, weak) UILabel* currentTmeLabel;

@property (nonatomic, weak) UITextView* textView;
@property (nonatomic, weak) UILabel* placeHolderLabel;

@property (nonatomic, weak) YWPhotoView* imageV;
@property (nonatomic, strong) NSMutableArray* totalImageNameArray;
@property (nonatomic, assign) CGFloat contentSizeHeight;

@property (nonatomic, weak) UIButton* arriveButton;
@property (nonatomic, weak) UIButton* leaveButton;

@property (nonatomic, strong) NSDateFormatter* dateFormatter;
@property (nonatomic, weak) MBProgressHUD* HUD;

@property (nonatomic, weak) UILabel* promptLabel;

//定位位置
@property (nonatomic, strong) CLLocation* clMapLocation;
@end

@implementation YWAttendanceViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = NSLocalizedString(@"arrive", nil);//@"签到";
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self layoutSubViews];
    [self location];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)location{
    self.locationLabel.text = NSLocalizedString(@"noPosition", nil);//@"暂无定位";
    //[[YWLocationManager shareManager] setUpLocationAccuracy:kCLLocationAccuracyHundredMeters];
    BOOL enable = [CLLocationManager locationServicesEnabled];
    int status = [CLLocationManager authorizationStatus];
    YWWeakSelf(weakSelf);
    if ( enable && ( status == kCLAuthorizationStatusAuthorizedWhenInUse)) {
        weakSelf.locationLabel.text = NSLocalizedString(@"positioning", nil);//@"正在定位中...";
        [[YWLocationManager shareManager] locationInfoWithCompletionBlock:^(NSString* locationInfo, NSError* error, CLLocation* location) {
            CGFloat locationW = SCREEN_WIDTH - CGRectGetMaxX(weakSelf.locationIV.frame) - 3 - kMarginW;
            CGFloat locationH = [YWCommonTool getHeightOfLabel:locationInfo andWidth:locationW andFont:weakSelf.locationLabel.font andMinHeight:kLabelH];
            if (locationH>kLabelH && locationH<kLabelH*2) {
                weakSelf.locationLabel.height = locationH;
            }else if (locationH > kLabelH*2){
                weakSelf.locationLabel.height = kLabelH*2;
            }
            locationText = locationInfo;
            weakSelf.locationLabel.text = locationInfo;
            weakSelf.clMapLocation = location;
        }];
    }
    else if (status == kCLAuthorizationStatusDenied) {
        weakSelf.locationLabel.text = NSLocalizedString(@"accessLocationsAreNotAllowed", nil);//@"不允许访问位置信息";
    }
    else if (!iOS8 && (!enable || status<3)){
        [[YWLocationManager shareManager] locationInfoWithCompletionBlock:^(NSString* locationInfo, NSError* error, CLLocation* location) {
            weakSelf.locationLabel.text = locationInfo;
        }];
    }
}

- (NSDateFormatter*)dateFormatter
{
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
        [_dateFormatter setDateFormat:@"HH:mm yyyy/MM/dd"];
    }
    return _dateFormatter;
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:self.view];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextAttendanceStart, nil);
        hud.dimBackground = YES;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.view addSubview:hud];
    }
    return _HUD;
}
- (NSMutableArray*)totalImageNameArray
{
    if (!_totalImageNameArray) {
        _totalImageNameArray = [NSMutableArray array];
    }
    return _totalImageNameArray;
}
- (UIScrollView*)myScrollView
{
    if (!_myScrollView) {
        UIScrollView* scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
        scrollView.delegate = self;
        [self.view addSubview:scrollView];
//        _myScrollView.canCancelContentTouches = NO;
        _myScrollView = scrollView;
    }
    return _myScrollView;
}
- (UIView*)bgView
{
    if (!_bgView) {
        UIView* bgView = [[UIView alloc] init];
        bgView.backgroundColor = [UIColor whiteColor];
        [bgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickBgViewEvent:)]];
        [self.myScrollView addSubview:bgView];
        _bgView = bgView;
    }
    return _bgView;
}

- (UIImageView*)locationIV
{
    if (!_locationIV) {
        UIImageView* locationImageV = [[UIImageView alloc] init];
        locationImageV.image = [UIImage imageNamed:@"common_location"];
        [self.bgView addSubview:locationImageV];
        _locationIV = locationImageV;
    }
    return _locationIV;
}

- (UILabel*)locationLabel
{
    if (!_locationLabel) {
        UILabel* locationLabel = [[UILabel alloc] init];
        locationLabel.font = kContentFont;
        locationLabel.numberOfLines = 2;
        [self.bgView addSubview:locationLabel];
        _locationLabel = locationLabel;
    }
    return _locationLabel;
}

-(UILabel *)currentTmeLabel{
    if (!_currentTmeLabel) {
        UILabel* currentTmeLabel = [[UILabel alloc] init];
        currentTmeLabel.font = [UIFont systemFontOfSize:16];
        currentTmeLabel.textAlignment = NSTextAlignmentCenter;
        NSString* dateTime = [self.dateFormatter stringFromDate:[NSDate date]];
        currentTmeLabel.text = [NSString stringWithFormat:@"%@: %@",NSLocalizedString(@"attendanceTime", nil),dateTime];
        [self.bgView addSubview:currentTmeLabel];
        _currentTmeLabel = currentTmeLabel;
    }
    return _currentTmeLabel;
}

- (UILabel*)promptLabel
{
    if (!_promptLabel) {
        UILabel* promptLabel = [[UILabel alloc] init];
        promptLabel.font = [UIFont systemFontOfSize:13];
        promptLabel.textAlignment = NSTextAlignmentCenter;
        promptLabel.textColor = [UIColor customTextGrayColor];
        promptLabel.text = NSLocalizedString(@"attendanceTips", nil);//@"请点击签到或签退，完成打卡\n如有其它特殊原因，请在备注说明\n请按公司要求选择是否拍照上传";
        promptLabel.numberOfLines = 0;
        [self.bgView addSubview:promptLabel];
        _promptLabel = promptLabel;
    }
    return _promptLabel;
}

- (UIImageView*)attendanceIV
{
    if (!_attendanceIV) {
        UIImageView* imageView = [[UIImageView alloc] init];
        imageView.image = [UIImage imageNamed:@"scan_select"];
        [self.bgView addSubview:imageView];
        _attendanceIV = imageView;
    }
    return _attendanceIV;
}

- (UILabel*)attendanceMan
{
    if (!_attendanceMan) {
        UILabel* attendanceMan = [[UILabel alloc] init];
        attendanceMan.font = kContentFont;
        attendanceMan.text = [NSString stringWithFormat:@"%@: %@",NSLocalizedString(@"attendanceExecutor", nil), [YWLoginTool loginUser].userName];
        attendanceMan.textAlignment = NSTextAlignmentCenter;
        [self.bgView addSubview:attendanceMan];
        _attendanceMan = attendanceMan;
    }
    return _attendanceMan;
}

- (UILabel*)attendanceTime
{
    if (!_attendanceTime) {
        UILabel* attendanceTime = [[UILabel alloc] init];
        attendanceTime.font = kContentFont;
        attendanceTime.textAlignment = NSTextAlignmentCenter;
        NSTimeInterval currtentTimeInterval = [[NSDate date] timeIntervalSince1970] * 1000;
        NSString* timeText = [YWCommonTool showTimeWithNormalFormatter:currtentTimeInterval / 1000];
        attendanceTime.text = [NSString stringWithFormat:@"%@: %@", NSLocalizedString(@"attendanceTime", nil),timeText];
        [self.bgView addSubview:attendanceTime];
        _attendanceTime = attendanceTime;
    }
    return _attendanceTime;
}

- (UITextView*)textView
{
    if (!_textView) {
        UITextView* textView = [[UITextView alloc] init];
        textView.layer.borderColor = [UIColor lightGrayColor].CGColor;
        textView.layer.borderWidth = 1.0;
        textView.layer.masksToBounds = YES;
        textView.layer.cornerRadius = 4.0;
        textView.delegate = self;
        textView.font = kContentFont;
        [self.bgView addSubview:textView];
        _textView = textView;
    }
    return _textView;
}
- (UILabel*)placeHolderLabel
{
    if (!_placeHolderLabel) {
        UILabel* placeHolderLabel = [[UILabel alloc] init];
        placeHolderLabel.font = kContentFont;
        placeHolderLabel.textColor = [UIColor customTextGrayColor];
        placeHolderLabel.text = NSLocalizedString(@"writeSomethingElse", nil);//@"如有特殊情况,请备注说明";
        _placeHolderLabel = placeHolderLabel;
        [self.textView addSubview:placeHolderLabel];
    }
    return _placeHolderLabel;
}

-(YWPhotoView *)imageV{
    if (!_imageV) {
        YWPhotoView* imageV = [[YWPhotoView alloc] init];
        imageV.delegate = self;
        [self.bgView addSubview:imageV];
        _imageV = imageV;
    }
    return _imageV;
}

- (UIButton*)createButtonWithTitle:(NSString*)title handleFunc:(SEL)handleFunc
{
    UIButton* btn = [UIButton buttonWithType:UIButtonTypeSystem];
    [btn setBackgroundColor:[UIColor whiteColor]];
    [btn setTitle:title forState:UIControlStateNormal];
    btn.titleLabel.font = kBoldTitleFont;
    [btn setTitleColor:[UIColor customBlueColor] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateDisabled];
    [btn setBackgroundImage:[UIImage imageWithColor:[UIColor customBackgroudColor]] forState:UIControlStateDisabled];
    btn.layer.borderColor = [UIColor customBlueColor].CGColor;
    btn.layer.borderWidth = 1.0;
    btn.layer.masksToBounds = YES;
    btn.layer.cornerRadius = 5.0;
    [btn addTarget:self action:handleFunc forControlEvents:UIControlEventTouchUpInside];
    return btn;
}

- (UIButton*)arriveButton
{
    if (!_arriveButton) {
        UIButton* arriveButton = [self createButtonWithTitle:NSLocalizedString(@"arrive", nil) handleFunc:@selector(arriveButtonClickEvent)];
        [self.bgView addSubview:arriveButton];
        _arriveButton = arriveButton;
    }
    return _arriveButton;
}

- (UIButton*)leaveButton
{
    if (!_leaveButton) {
        UIButton* leaveButton = [self createButtonWithTitle:NSLocalizedString(@"leave", nil) handleFunc:@selector(leaveButtonClickEvent)];
        [self.bgView addSubview:leaveButton];
        _leaveButton = leaveButton;
    }
    return _leaveButton;
}

- (void)layoutSubViews
{
    CGFloat smallIconSize = 17;
    CGFloat textViewH = 75;
    [self.locationIV setFrame:CGRectMake(kMarginW, gap + 2, smallIconSize, smallIconSize)];
    CGFloat locationW = SCREEN_WIDTH - CGRectGetMaxX(self.locationIV.frame) - 3 - kMarginW;
    CGFloat locationH = [YWCommonTool getHeightOfLabel:self.locationLabel.text andWidth:locationW andFont:self.locationLabel.font andMinHeight:kLabelH];
    [self.locationLabel setFrame:CGRectMake(CGRectGetMaxX(self.locationIV.frame) + 3, gap, locationW, locationH)];
    [self.currentTmeLabel setFrame:CGRectMake(kMarginW, CGRectGetMaxY(self.locationLabel.frame) + gap * 3, locationW, kLabelH)];
    
//    [self.latestAttendanceTimeLabel setFrame:CGRectMake(kMarginW+3, CGRectGetMaxY(self.currentTmeLabel.frame)+gap*2, labelWidth-6, kLabelH)];
    [self.textView setFrame:CGRectMake(kMarginW, CGRectGetMaxY(self.currentTmeLabel.frame)+gap*2 , labelWidth, textViewH)];
    [self.placeHolderLabel setFrame:CGRectMake(5, 5, _textView.frame.size.width - 10, kLabelH)];
    
    [self.imageV setFrame:CGRectMake(0, CGRectGetMaxY(self.textView.frame) + gap, SCREEN_WIDTH, YWPhotoSize)];
    
    [self.arriveButton setFrame:CGRectMake(kMarginW, CGRectGetMaxY(self.imageV.frame) + gap * 2, labelWidth / 2 - kMarginW, kButtonH)];

    [self.leaveButton setFrame:CGRectMake(SCREEN_WIDTH / 2 + kMarginW, CGRectGetMaxY(self.imageV.frame) + gap * 2, labelWidth / 2 - kMarginW, kButtonH)];

    [self.promptLabel setFrame:CGRectMake(20, CGRectGetMaxY(self.leaveButton.frame) + gap * 2, SCREEN_WIDTH - 40, kLabelH * 3)];
    //最后的gap是留白
    _contentSizeHeight = gap + locationH + gap * 10 + self.currentTmeLabel.height + textViewH + gap + YWPhotoSize + kButtonH + self.promptLabel.height + gap;
    [self.bgView setFrame:CGRectMake(0, kGapH, SCREEN_WIDTH, _contentSizeHeight)];
    
    self.myScrollView.contentSize = CGSizeMake(SCREEN_WIDTH, self.bgView.height+kGapH*2);
}

#pragma mark - YWPhotoViewDelegate
- (void)resetPhotoViewFrame:(CGRect)rect andTotalPhotoArray:(NSArray *)photoNameArray{
    [self.totalImageNameArray removeAllObjects];
    [self.totalImageNameArray addObjectsFromArray:photoNameArray];
    
    self.imageV.frame = CGRectMake(0, CGRectGetMaxY(self.textView.frame) + kGapH, SCREEN_WIDTH, rect.size.height);
    if (photoNameArray.count>=4) {
        self.bgView.height = _contentSizeHeight + YWPhotoGap + YWPhotoSize;
        self.myScrollView.contentSize = CGSizeMake(SCREEN_WIDTH, self.bgView.height+kGapH*2);
    }else{
        self.bgView.height = _contentSizeHeight;
        self.myScrollView.contentSize = CGSizeMake(SCREEN_WIDTH, self.bgView.height+kGapH*2);
    }
    self.arriveButton.y = CGRectGetMaxY(self.imageV.frame) + gap * 2;
    self.leaveButton.y = CGRectGetMaxY(self.imageV.frame) + gap * 2;
    self.promptLabel.y = CGRectGetMaxY(self.leaveButton.frame) + gap * 2;

}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //键盘弹起的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    //键盘隐藏的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}
- (void)clickBgViewEvent:(id)sender{
    [self.view endEditing:YES];
}
#pragma mark - UIKeyboardNSNotification
- (void)keyboardWillShow:(NSNotification*)notification
{
    NSDictionary* info = [notification userInfo];
    NSValue* value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    [self moveUpBgViewWithKeyboardHeight:keyboardSize.height animationDuration:duration];
}

- (void)keyboardWillHide:(NSNotification*)notification
{
    NSDictionary* info = [notification userInfo];
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    [self moveDownBgViewWithDuration:duration];
}
- (void)moveUpBgViewWithKeyboardHeight:(CGFloat)height animationDuration:(CGFloat)duration
{
    CGRect parentRect = [self.bgView convertRect:self.textView.frame toView:self.view];
    CGFloat textViewMaxY = CGRectGetMaxY(parentRect);
    if (SCREEN_HEIGHT - textViewMaxY >= height) {
        return;
    }
    [UIView animateWithDuration:duration animations:^{
        self.bgView.y = -(height - SCREEN_HEIGHT + textViewMaxY);
    }];
}

- (void)moveDownBgViewWithDuration:(CGFloat)duration
{
    if (kGapH == self.bgView.y) {
        return;
    }
    [UIView animateWithDuration:duration animations:^{
        self.bgView.y = kGapH;
    }];
}
#pragma mark - textViewDelegate
- (void)textViewDidChange:(UITextView*)textView
{
    if (textView.text.length == 0) {
        self.placeHolderLabel.hidden = NO;
    }
    else {
        self.placeHolderLabel.hidden = YES;
    }
    NSString *toBeString = textView.text;
    
    //获取高亮部分
    UITextRange *selectedRange = [textView markedTextRange];
    UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
    
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position)
    {
        if (toBeString.length > KDescriptionTextMax)
        {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:KDescriptionTextMax];
            if (rangeIndex.length == 1)
            {
                textView.text = [toBeString substringToIndex:KDescriptionTextMax];
            }
            else
            {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, KDescriptionTextMax)];
                textView.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}

- (void)updateShowView:(NSNotification*)info
{
//    self.dateLabel.hidden = YES;
//    self.timeLabel.hidden = YES;
    
    self.currentTmeLabel.hidden = YES;
    self.textView.hidden = YES;
    self.placeHolderLabel.hidden = YES;
    self.arriveButton.hidden = YES;
    self.leaveButton.hidden = YES;
//    self.latestAttendanceTimeLabel.hidden = YES;
    self.imageV.hidden = YES;

    [self.attendanceIV setFrame:CGRectMake((SCREEN_WIDTH - imageSize) / 2, CGRectGetMaxY(self.locationLabel.frame) + gap * 2, imageSize, imageSize)];
    [self.attendanceMan setFrame:CGRectMake(kMarginW, CGRectGetMaxY(self.attendanceIV.frame) + gap * 2, labelWidth, kLabelH)];
    [self.attendanceTime setFrame:CGRectMake(kMarginW, CGRectGetMaxY(self.attendanceMan.frame) + gap * 2, labelWidth, kLabelH)];

    self.attendanceTime.text = info.userInfo[@"dateTime"];
}

//- (void)stopTimer
//{
//    [self.timer invalidate];
//    self.timer = nil;
//}

- (void)recordButtonClickEvent
{
    YWAttendanceRecordViewController* attendanceRecordViewController = [[YWAttendanceRecordViewController alloc] init];
    [self.navigationController pushViewController:attendanceRecordViewController animated:YES];
}

- (void)arriveButtonClickEvent
{
    [self CheckBeforeArrivaOrLeave:YWAttendanceTypeArrive];
}

- (void)leaveButtonClickEvent
{
    [self CheckBeforeArrivaOrLeave:YWAttendanceTypeLeave];
}

- (void)CheckBeforeArrivaOrLeave:(YWAttendanceType)type{
    NSMutableArray *loginInfos = [[NSUserDefaults standardUserDefaults] objectForKey:@"loginInformation"];
    if (loginInfos) {
        NSString *lastUniqueIdStr = loginInfos[0];
        NSInteger lastUniqueId = [lastUniqueIdStr integerValue];
        NSString *lastTime = loginInfos[1];
        double lastLoginTime = [lastTime doubleValue];
        NSInteger nowUniqueId = [YWLoginTool loginUser].uniqueId;
        
        NSTimeInterval nowTime = [[NSDate date] timeIntervalSince1970];
        long long timeJetlag = nowTime - lastLoginTime;
        NSString * title = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"youShouldNotChangeUserAccountFrequently", nil),type == YWAttendanceTypeArrive ? NSLocalizedString(@"arrive", nil) : NSLocalizedString(@"leave", nil)];
        if (nowUniqueId != lastUniqueId && timeJetlag < 900) {
            UIAlertController* alertController= [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
            [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:nil]];
            [self presentViewController:alertController animated:YES completion:nil];
        }else{
            [self attendanceQRCodeReader:type];
        }
    }else{
        [self attendanceQRCodeReader:type];
    }
}

//- (NSString*)savefilePath:(NSString*)fileName
//{
//    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:fileName];
//    return filePath;
//}

- (void)attendanceQRCodeReader:(YWAttendanceType)type{
    [self.view endEditing:YES];
    NSString* note = [_textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if ([YWCommonTool isContainsEmoji:note]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    [self.HUD show:YES];
    
    NSString *coordinate = [NSString stringWithFormat:@"%f,%f",self.clMapLocation.coordinate.latitude,self.clMapLocation.coordinate.longitude];
    
    YWAttendanceRecord *record = [[YWAttendanceRecord alloc] init];
    record.arriveRemark = note;
    record.type = type;
    record.qrcodeId = self.qrcodeId;
    record.locationId = self.locationId;
    record.recordId = [YWCommonTool randStringId];
    record.arriveTime = [[NSDate date] timeIntervalSince1970];
//    NSTimeInterval systemUptime =[[NSProcessInfo processInfo] systemUptime];//获取运行该进程的系统已运行的时间，单位是秒
//    [NSKeyedArchiver archiveRootObject:@(systemUptime) toFile:[self savefilePath:KYWRememberSystemUptime]];
    
    NSInteger uniqueId = [YWLoginTool loginUser].uniqueId;
    NSArray * loginInfos = @[@(uniqueId),@(record.arriveTime)];
    [[NSUserDefaults standardUserDefaults] setObject:loginInfos forKey:@"loginInformation"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    record.locationText = locationText.length ? locationText : nil;
    record.coordinate = coordinate;
    NSDate* attendanceDate = [NSDate dateWithTimeIntervalSince1970:record.arriveTime];
    record.yearMonthDay = [[NSString stringWithFormat:@"%ld%.2ld%.2ld", (long)attendanceDate.year, (long)attendanceDate.month,(long)attendanceDate.day] integerValue];
    ;
    record.dateShow = [NSString stringWithFormat:@"%.2ld月%.2ld日 %@", (long)attendanceDate.month, (long)attendanceDate.day, [YWCommonTool weekDayString:attendanceDate.weekday - 1]];
    ;
    record.uploadStatus = YWAttendanceUploadStatusUploading;
//    BOOL saveRecord = [[YWAttendanceManager shareManager] updateAttendanceRecordWithRecord:record];
    NSArray *pictures = [self createPicturesWithAttendanceRecord:record];
//    BOOL savePictures = [[YWMeterReadingManager shareManager] updatePatrolPictureWithArray:pictures];
//    if (savePictures && saveRecord) {
    
        [[YWAttendanceManager shareManager] submitAttendanceRecord:record pistures:pictures completeBlock:^(BOOL succeed) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.HUD hide:YES];
                if (succeed) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:KUpdateAttendanceUploadStatusNotification object:nil];
                    if (self.qrcodeId) {
                        [self.navigationController popViewControllerAnimated:YES];
                    }else{
                        UIViewController *vc = nil;
                        for (UIViewController *temp in self.navigationController.viewControllers) {
                            if ([temp isKindOfClass:[YWMyAttendanceViewController class]]) {
                                vc = temp;
                                break;
                            }
                        }
                        if (vc) {
                            [self.navigationController popToViewController:vc animated:YES];
                        }else{
                            [self.navigationController popViewControllerAnimated:YES];
                        }
                    }
                }else{
                    [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"kTextCommitFailed", nil)];
                }
            });
        }];
    
        
//    }else {
//        [self.HUD hide:YES];
//        YWLog(@"保存数据库失败");
//    }
    
}

- (NSArray*)createPicturesWithAttendanceRecord:(YWAttendanceRecord*)record
{
    NSMutableArray* pictures = [NSMutableArray array];
    for (int i = 0; i < [self.totalImageNameArray count]; i++) {
        YWPatrolPicture* picture = [[YWPatrolPicture alloc] init];
        picture.recordId = record.recordId;
        picture.pictureId = [YWCommonTool randStringId];
        picture.pictureName = self.totalImageNameArray[i];
        picture.isLocalImage = YES;
        picture.uploadStatus = YWPictureRecordUploadStatusNull;
        picture.recordType = YWPictureRecordTypeAttendance;
        [pictures addObject:picture];
    }
    return pictures;
}

//- (void)attendanceBtnEnable
//{
//    if ([[YWAttendanceManager shareManager] attendanceOperateType] == YWAttendanceOperateTypeCanArrive) {
//        self.arriveButton.enabled = YES;
//        self.leaveButton.enabled = NO;
//    }
//    else if ([[YWAttendanceManager shareManager] attendanceOperateType] == YWAttendanceOperateTypeCanLeave) {
//        [self.arriveButton setTitle:@"已签到" forState:UIControlStateNormal];
//        self.arriveButton.enabled = NO;
//        self.leaveButton.enabled = YES;
//    }
//}
@end
